package com.project.common.core.utils.apple;

import com.alibaba.fastjson.JSONObject;
import com.project.common.core.config.prop.PropAttributes;
import com.project.common.core.config.prop.PropConfig;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;

/**
 * 阿里支付工具类
 *
 * @author WYY
 * @date 2021/02/18
 */
public class ApplePayUtil {
    /**
     * 日志工具类
     */
    public static Logger log = LoggerFactory.getLogger(ApplePayUtil.class);

    /**
     * Apple Pay验证网关
     */
    public static final String APPLE_PAY_GATEWAY = PropConfig.getProperty(PropAttributes.THIRDPARTY_APPLE_PAY_GATEWAY);

    /**
     * 验证苹果支付订单
     *
     * @param receiptData 接受
     * @return 苹果支付检验返回状态码 描述
     * 21000 App Store无法读取你提供的JSON数据
     * 21002 收据数据不符合格式
     * 21003 收据无法被验证
     * 21004 你提供的共享密钥和账户的共享密钥不一致
     * 21005 收据服务器当前不可用
     * 21006 收据是有效的，但订阅服务已经过期。当收到这个信息时，解码后的收据信息也包含在返回内容中
     * 21007 收据信息是测试用（sandbox），但却被发送到产品环境中验证
     * 21008 收据信息是产品环境中使用，但却被发送到测试环境中验证
     */
    public static JSONObject verifyPayData(String receiptData) {
        try {
            HttpsURLConnection connection = (HttpsURLConnection) new URL(APPLE_PAY_GATEWAY).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setAllowUserInteraction(false);
            PrintStream ps = new PrintStream(connection.getOutputStream());
            ps.print("{\"receipt-data\": \"" + receiptData + "\"}");
            ps.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            StringBuffer sb = new StringBuffer();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
            String resultStr = sb.toString();
            JSONObject result = JSONObject.parseObject(resultStr);
            if (result != null && result.getInteger("status") == 21007) {   //递归，以防漏单
                return verifyPayData(receiptData);
            }
            return result;
        } catch (Exception e) {
            log.error("\r\n *********** Apple Pay 验证订单出错:{}", ExceptionUtils.getFullStackTrace(e));
        }
        return null;
    }
}
